package com.example.prom.qianduoduo.y2025.controller;

import io.github.bonigarcia.wdm.WebDriverManager;
import lombok.extern.slf4j.Slf4j;
import org.openqa.selenium.Cookie;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.support.ui.WebDriverWait;

import java.net.URL;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.Duration;
import java.util.*;

/**
 * Description
 *
 * @author DangWen
 */
@Slf4j
public class BaseController {

    public static Map<String, String> createHeaders() {
        Map<String, String> headers = new HashMap<>();
        headers.put("Accept-Language","zh-CN,zh;q=0.9");
        headers.put("Cookie","Hm_lvt_36f2f0446e1c2cda8410befc24743a9b=1751339940,1751416952,1751419643; HMACCOUNT=8134B8F59C308B5F; Hm_lpvt_36f2f0446e1c2cda8410befc24743a9b=1751420045");
        headers.put("Accept-Encoding","gzip, deflate, br, zstd");
        headers.put("Referer","https://dbba.sacinfo.org.cn/stdList");
        headers.put("Accept","application/json, text/javascript, */*; q=0.01");
        headers.put("Content-Type","application/x-www-form-urlencoded");
        headers.put("X-Requested-With","XMLHttpRequest");
        headers.put("sec-ch-ua-mobile","?0");
        headers.put("sec-ch-ua-platform","\"Windows\"");
        headers.put("sec-ch-ua","\"Google Chrome\";v=\"137\", \"Chromium\";v=\"137\", \"Not/A)Brand\";v=\"24\"");
        headers.put("User-Agent","Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/137.0.0.0 Safari/537.36");
        headers.put("sec-fetch-site","same-origin");
        headers.put("sec-fetch-mode","cors");
        headers.put("sec-fetch-dest","empty");
        headers.put("Host","dbba.sacinfo.org.cn");
        headers.put("Connection","keep-alive");
        headers.put("Origin","https://dbba.sacinfo.org.cn");
        return headers;
    }

    /**
     * 初始化 WebDriver
     */
    private static WebDriver webDriverInstance = null;

    public static WebDriver getWebDriver() {
       return getWebDriver(null, null);
    }

    public static WebDriver getWebDriver(String cookie, String url) {
        if (webDriverInstance == null) {
            Path path = Paths.get("00dowin/src/main/resources/static/chromedriver.exe");
            System.setProperty("webdriver.chrome.driver", String.valueOf(path.toAbsolutePath()));
            ChromeOptions options = new ChromeOptions();
            options.addArguments(
                    "--user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36",
                    "--window-size=1920,1080",
                    "--lang=zh-CN,zh;q=0.9",
                    "--disable-gpu",
                    "--disable-blink-features=AutomationControlled",
                    "--remote-allow-origins=*",
                    "--disable-web-security",
                    "--allow-running-insecure-content",
                    "--disable-extensions",
                    "--no-sandbox",
                    "--Accept-Encoding=gzip, deflate, br, zstd",
                    "--disable-popup-blocking",
                    "--disable-dev-shm-usage",
                    "--disable-setuid-sandbox",
                    "--disable-features=ImprovedCookieControls,LazyFrameLoading,GlobalMediaControls,DestroySessionOnDomainChange,MediaRouter,MediaHistory,HardwareMediaKeyHandling,HardwareKeyboard",
                    "--disable-features=IsolateOrigins,site-per-process",
                    "--Sec-Fetch-Dest=empty",
                    "--Sec-Fetch-Mode=cors",
                    "--Sec-Fetch-Site=same-origin",
                    "--Sec-Fetch-User=?1",
                    "--sec-ch-ua=Google Chrome\";v=\"137\", \"Chromium\";v=\"137\", \"Not/A)Brand\";v=\"24",
                    "--sec-ch-ua-platform=Windows"

            );
            options.setExperimentalOption("excludeSwitches", Arrays.asList("enable-automation", "load-extension", "enable-logging"));
            options.setExperimentalOption("useAutomationExtension", false);
            webDriverInstance = new ChromeDriver(options);
            // 添加Cookie处理
            if (cookie != null && !cookie.isEmpty()) {
                webDriverInstance.get(url); // 先访问网站才能设置Cookie
                log.info("getWebDriver url:{},  cookie:{}", url, cookie);
                Set<Cookie> cookieSet = parseCookies(cookie, url);
                for (Cookie c : cookieSet) {
//                    log.info("addCookie, name:{}, value:{}, domain:{}", c.getName(),c.getValue(),c.getDomain());
                    webDriverInstance.manage().addCookie(c);
                }
            }
        }
        return webDriverInstance;
    }

//    public static WebDriverWait getWebDriverWait(){
//        return new WebDriverWait(webDriverInstance, Duration.ofSeconds(30));
//    }



    public static WebDriverWait newWebDriverWait() {
        return new WebDriverWait(getWebDriver(), Duration.ofSeconds(30));
    }

    // 解析Cookie字符串为Cookie对象集合
    private static Set<Cookie> parseCookies(String cookieString, String url) {
        Set<Cookie> cookies = new HashSet<>();
        String[] cookiePairs = cookieString.split(";");
        for (String pair : cookiePairs) {
            String[] keyValue = pair.trim().split("=", 2);
            if (keyValue.length == 2) {
                String name = keyValue[0];
                String value = keyValue[1];
                Cookie cookie = new Cookie.Builder(name, value.replace("\t", " "))
                        .domain(extractDomainFromUrl(url))
                        .path("/")
                        .build();
                cookies.add(cookie);
            }
        }
        return cookies;
    }

    private static String extractDomainFromUrl(String url) {
        try {
            URL u = new URL(url);
            String host = u.getHost();
            return host.startsWith("www.") ? host.substring(4) : host;
        } catch (Exception e) {
            return "db.yaozh.com";
        }
    }
}
